package com.example.mypic;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.example.mypic.adapters.PicAdapter;
import com.example.mypic.models.IPWallpaperImage;
import com.example.mypic.models.PicHelper;
import com.example.mypic.utils.Utils;

public class AllPicActivity extends ListActivity {
	private List<IPWallpaperImage> models;
	private PicAdapter adapter;
	private PicHelper helper;
	private ProgressDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);

		models = Utils.pics;
		new PicTask().execute();

		// adapter = new PicAdapter(AllPicActivity.this, R.layout.pic, models);

		helper = new PicHelper(this);
	}

	private class PicTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			// String link =
			// "http://itechforlife.com/3DWallpapers.asmx/GetImageListTopDownloadByDevice?sDevice=iphone";

			// models = PicParser.parse(link, AllPicActivity.this);

			adapter = new PicAdapter(AllPicActivity.this, R.layout.pic, models);

			return null;
		}

		protected void onPostExecute(Void result) {

			super.onPostExecute(result);
			setListAdapter(adapter);
			// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		};
	};

	@Override
	protected void onListItemClick(ListView l, View v, final int position,
			long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);

		// Toast.makeText(getApplicationss
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Cursor c = helper.getByImageID(models.get(position)
						.getImageID());
				if (c.getCount() <= 0) {
					models.get(position).setLastViewTime(
							System.currentTimeMillis());
					helper.insert(models.get(position));
				} else {
					helper.update(models.get(position),
							System.currentTimeMillis());
				}

			}
		});
		if (Utils.recent.containsKey(models.get(position).getImageID())) {
			Intent intent = new Intent("android.intent.action.DETAIL");
			intent.putExtra(Utils.KEY, models.get(position).getImageID());
			startActivity(intent);
		} else {
			dialog = ProgressDialog.show(AllPicActivity.this, "", "Loading...");
			new DetailTask().execute(position);
		}
	}

	private class DetailTask extends AsyncTask<Integer, Void, Boolean> {
		private int position;

		@Override
		protected Boolean doInBackground(Integer... params) {
			// TODO Auto-generated method stub
			position = params[0];
			IPWallpaperImage wall = models.get(position);
			String linkImage = wall.getImage();
			try {
				InputStream is = (InputStream) new URL(linkImage).getContent();
				Drawable drawable = Drawable.createFromStream(is, "iamge_"
						+ wall.getImageID());

				Utils.recent.put(models.get(position).getImageID(), drawable);
				return true;
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return false;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (dialog != null) {
				dialog.dismiss();
			}
			if (result) {
				Intent intent = new Intent("android.intent.action.DETAIL");
				intent.putExtra(Utils.KEY, models.get(position).getImageID());
				startActivity(intent);
			} else {
				Toast.makeText(AllPicActivity.this, "Không thể tải ảnh",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		if (item.getItemId() == R.id.recent) {
			Intent intent = new Intent("android.intent.action.RECENT");
			startActivity(intent);
		}
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		getMenuInflater().inflate(R.menu.all_pic, menu);
		return true;
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		if (helper != null) {
			helper.close();
		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		if (helper == null) {
			helper = new PicHelper(this);
		}
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if (helper != null) {
			helper.close();
		}
		super.onDestroy();
	}
}